package bdd;
/*
 * Programme   : ControleurSGBD.java
 * Date        : 01.04.2011
 * Auteur(s)   : ARBELET Alexandre, MOEGLI Thomas, VIBERT Sandy
 *
 * Description : Gere l'execution des requetes sql sur une base de donnee
 *
 */


import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 *
 * @author Sandy
 */
public class ControleurSGBD {

	private String dbURL = "";
	private String user = "";
	private String password = "";
	private java.sql.Connection dbConnect = null;
	private java.sql.Statement dbStatement = null;

	/**
	 * Constructeur
	 * @param url
	 * @param user
	 * @param password
	 */
	public ControleurSGBD(String url, String user, String password) {
		this.dbURL = url;
		this.user = user;
		this.password = password;
	}

	/**
	 * Connecter à la base de donnée
	 * @return false en cas d'échec
	 */
	public Boolean connect() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			this.dbConnect = DriverManager.getConnection("jdbc:mysql:" + this.dbURL, this.user, this.password);
			this.dbStatement = this.dbConnect.createStatement();
			return true;
		} catch (SQLException ex) {
			System.out.println("Database Error : " + ex);
		} catch (ClassNotFoundException ex) {
			System.out.println("Driver Error : " + ex);
		}
		return false;
	}

	/**
	 * Executer une requete SQL de type recherche
	 * @param sql
	 * @return resultat de la requete
	 */
	public ResultSet executionRequete(String sql){

		try {
			ResultSet rs = this.dbStatement.executeQuery(sql);
			return rs;
		} catch (SQLException ex) {
			System.out.println("Database Error : " + ex);
		}
		return null;
	}

	public int execModify(String sql) {
		try {
			return this.dbStatement.executeUpdate(sql);
		} catch (SQLException ex) {
			System.out.println("Database Error : " + ex);
		}
		return 0;
	}

	/**
	 * Executer une requete SQL de type modification ou procedure
	 * @param sql
	 * @return 1 si tout s'est bien passé, 0 sinon
	 */
	public int executionRequeteModify(String sql){

		try {
			return this.dbStatement.executeUpdate(sql);
		} catch (SQLException ex) {
			System.out.println("Database Error : " + ex);
		}
		return 0;

	}

	/**
	 * Fermer la connexion au serveur de DB
	 */
	public void close() {
		try {
			this.dbStatement.close();
			this.dbConnect.close();
			this.dbConnect.close();
		} catch (SQLException ex) {
			System.out.println("Database Error : " + ex);
		}
	}
}

